<?php

namespace app\controller\admin\module\login;

use app\controller\admin\module\BaseController;
use think\exception\ValidateException;
use think\response\Json;
use think\response\View;

class Index extends BaseController
{
    /**
     * 登录页面
     * @return View
     */
    public function index(): View
    {
        return fetch('/admin/login/index');
    }

    /**
     * 登录验证
     * @return Json
     */
    public function login(): Json
    {
        if(getCaches(session('token'), [])){
            return responseMsg('您已登录，页面即将跳转~', 204, [], [], url('/admin/index')->build());
        }
        $name = $this->request->post('username');
        $pwd = $this->request->post('password');
        $captcha = $this->request->post('captcha');
        try {
            $this->validate([
                'name' => $name,
                'pwd' => $pwd,
                'captcha' => $captcha,
            ], [
                'name|用户名' => 'require',
                'pwd|密码' => 'require',
                'captcha|验证码' => 'require|captcha',
            ]);
            $info = Model('admin')->getInfo(['name' => $name, 'status' => 1], 'id, salt, pwd, avatar, name, nick, email, gid, is_super, login_num, token');
            if(empty($info) or !password_verify(sha1($info['salt'] . $pwd), $info['pwd'])){
                return responseMsg('账号/密码错误');
            }
            $this->updateAdmin($info);
            putAdminLog('管理员登录['.$info['id'].']['.$info['name'].']');
            return responseMsg('登录成功，页面即将跳转~', 200, [], [], url('/admin/index')->build());
        }catch (ValidateException $e){
            return responseMsg($e->getError());
        }
    }

    /**
     * 更新管理员信息
     * @param $data
     * @return void
     */
    private function updateAdmin($data){
        deleteToken($data['token']);  //删除之前的redis token登录状态
        $data['token'] = md5(generateToken() . $data['id'] . $data['name'] . time());
        Model('admin')->edit([
            'id' => $data['id']
        ], [
            'token' => $data['token'],
            'login_num' => $data['login_num'] + 1,
            'last_login_time' => time(),
            'last_login_ip' => $this->request->ip()
        ]);
        session('token', $data['token']);
        $this->setLoginData($data['token'], [
            'id' => $data['id'],
            'token' => $data['token'],
            'avatar' => $data['avatar'],
            'nick' => $data['nick'],
            'name' => $data['name'],
            'email' => $data['email'],
            'gid' => $data['gid'],
            'is_super' => $data['is_super'],
            'auth' => $this->makeMyAuth($data['gid']),
        ]);
    }


    /**
     * 登出
     * @return Json|null
     */
    public function logout(): ?Json
    {
        putAdminLog('管理员' . (getCaches(session('token'), []) ? getCaches(session('token'), [])['name'] : null) . '退出登录');
        deleteToken(session('token'));
        return loginFailure();
    }
}